package data;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import exception.ServerDownException;

/**
 * Security methods.
 */
public class Security 
{
	// <! - Methods - >
	/**
	 * Deciphers text.
	 */
	public static String decrypt(String text, byte[] sc) throws ServerDownException
	{
		SecretKey ky = new SecretKeySpec(sc, "AES");
		byte[] ec = Base64.decodeBase64(text.getBytes());
		
		try
		{
			Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
			c.init(Cipher.DECRYPT_MODE, ky);
			return new String(c.doFinal(ec));
		}
		catch(Exception e)
		{
			throw new ServerDownException(e.getLocalizedMessage());
		}
	}
	
	/**
	 * Ciphers text.
	 */
	
	public static String encrypt(String text, byte[] sc) throws ServerDownException
	{
		SecretKey ky = new SecretKeySpec(sc, "AES");
		
		try
		{
			Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
			c.init(Cipher.ENCRYPT_MODE, ky);
			return new String(Base64.encodeBase64(c.doFinal(text.getBytes())));
		}
		catch(Exception e)
		{
			throw new ServerDownException(e.getLocalizedMessage());
		}	
	}
	
	/**
	 * Sanitize a string, prevent SQL injection.
	 */
	public static String sanitize(String arg0)
	{
		arg0 = arg0.replace("\\", "\\\\");
		return arg0.replace("'", "\\'");
	}
}
